import { constantRoutes } from '@/router'
import { getMenu } from '@/api/login'
import _import from '@/store/modules/_import'

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data) {
    try {
        data.forEach(item => {
            const menu = {
                path: item.path,
                component: _import(item.component),
                hidden: item.hiddenFlag === 1 ? true : false,
                children: [],
                alwaysShow: true,
                name: item.path,//加name是为了在面包屑中可以显示当前的侧边栏名称
                meta: { title: item.title, icon: item.icon }
            }
            if (item.children) {
                generaMenu(menu.children, item.children)
            }
            routes.push(menu)
        })
    } catch (e) {
        console.log(e)
    }
}

const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    }
}

const actions = {
    async generateRoutes({ commit }) {
        // 取后台路由
        const asyncRouter = await getMenu()
        return new Promise(resolve => {
            const tmp = asyncRouter.data
            if (tmp) {
                let accessedRoutes = []
                generaMenu(accessedRoutes, tmp)
                commit('SET_ROUTES', accessedRoutes)
                resolve(accessedRoutes)
            }

        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
